/**
 * Electron文件系统存储适配器
 *
 * 通过IPC与主进程的SQLite存储通信
 * 实现StorageAdapter接口，无缝集成到现有系统
 */

import type { Content, ContentType, ContentStatus } from '../../../types/document'
import type {
  ContentListItem,
  StorageResult
} from '../types'
import { StorageErrorCode } from '../storageErrors'

/**
 * Electron文件系统适配器
 * 注意: 不实现StorageAdapter接口，因为Electron IPC是异步的
 * StorageFactory会智能识别并正确使用此适配器
 */
export class ElectronFSAdapter {
  /**
   * 检查Electron API是否可用
   */
  private checkElectronAPI(): void {
    if (typeof window === 'undefined' || !window.electronAPI?.storage) {
      throw new Error('Electron API不可用')
    }
  }

  /**
   * 保存内容
   */
  async saveContent(content: Content): Promise<StorageResult<void>> {
    try {
      this.checkElectronAPI()
      const result = await window.electronAPI.storage.save(content)
      return result
    } catch (error) {
      return {
        ok: false,
        error: {
          code: StorageErrorCode.UNKNOWN,
          message: error instanceof Error ? error.message : '保存失败'
        }
      }
    }
  }

  /**
   * 通过ID获取内容
   */
  async getContentById(id: string): Promise<StorageResult<Content | null>> {
    try {
      this.checkElectronAPI()
      const result = await window.electronAPI.storage.get(id)
      return result
    } catch (error) {
      return {
        ok: false,
        error: {
          code: StorageErrorCode.UNKNOWN,
          message: error instanceof Error ? error.message : '获取失败'
        }
      }
    }
  }

  /**
   * 删除内容
   */
  async removeContent(id: string): Promise<StorageResult<void>> {
    try {
      this.checkElectronAPI()
      const result = await window.electronAPI.storage.delete(id)
      return result
    } catch (error) {
      return {
        ok: false,
        error: {
          code: StorageErrorCode.UNKNOWN,
          message: error instanceof Error ? error.message : '删除失败'
        }
      }
    }
  }

  /**
   * 获取内容列表
   */
  async getContents(options: {
    type?: ContentType[]
    status?: ContentStatus[]
    sortBy?: 'createdAt' | 'updatedAt' | 'title'
    sortOrder?: 'asc' | 'desc'
  }): Promise<StorageResult<ContentListItem[]>> {
    try {
      this.checkElectronAPI()
      const result = await window.electronAPI.storage.list(options)
      return result
    } catch (error) {
      return {
        ok: false,
        error: {
          code: StorageErrorCode.UNKNOWN,
          message: error instanceof Error ? error.message : '获取列表失败'
        }
      }
    }
  }

  /**
   * 获取最近的内容列表
   */
  async listRecent(limit = 20): Promise<StorageResult<ContentListItem[]>> {
    try {
      this.checkElectronAPI()
      const result = await window.electronAPI.storage.listRecent(limit)
      return result
    } catch (error) {
      return {
        ok: false,
        error: {
          code: StorageErrorCode.UNKNOWN,
          message: error instanceof Error ? error.message : '获取最近列表失败'
        }
      }
    }
  }

  /**
   * 按类型过滤内容
   */
  async filterByType(type: ContentType): Promise<StorageResult<ContentListItem[]>> {
    return this.getContents({ type: [type] })
  }

  /**
   * 按状态过滤内容
   */
  async filterByStatus(status: ContentStatus): Promise<StorageResult<ContentListItem[]>> {
    return this.getContents({ status: [status] })
  }

  /**
   * 按标题搜索内容
   */
  async searchByTitle(keyword: string): Promise<StorageResult<ContentListItem[]>> {
    try {
      this.checkElectronAPI()
      const result = await window.electronAPI.storage.search(keyword, 50)
      return result
    } catch (error) {
      return {
        ok: false,
        error: {
          code: StorageErrorCode.UNKNOWN,
          message: error instanceof Error ? error.message : '搜索失败'
        }
      }
    }
  }

  /**
   * 批量保存
   */
  async batchSave(contents: Content[]): Promise<StorageResult<void>> {
    try {
      this.checkElectronAPI()
      const result = await window.electronAPI.storage.batchSave(contents)
      return result
    } catch (error) {
      return {
        ok: false,
        error: {
          code: StorageErrorCode.UNKNOWN,
          message: error instanceof Error ? error.message : '批量保存失败'
        }
      }
    }
  }

  /**
   * 批量删除
   */
  async batchRemove(ids: string[]): Promise<StorageResult<void>> {
    try {
      this.checkElectronAPI()
      const result = await window.electronAPI.storage.batchDelete(ids)
      return result
    } catch (error) {
      return {
        ok: false,
        error: {
          code: StorageErrorCode.UNKNOWN,
          message: error instanceof Error ? error.message : '批量删除失败'
        }
      }
    }
  }

  /**
   * 获取统计信息
   */
  async getStats(): Promise<StorageResult<{
    totalDocuments: number
    byType: Record<string, number>
    byStatus: Record<string, number>
  }>> {
    try {
      this.checkElectronAPI()
      const result = await window.electronAPI.storage.getStats()
      return result
    } catch (error) {
      return {
        ok: false,
        error: {
          code: StorageErrorCode.UNKNOWN,
          message: error instanceof Error ? error.message : '获取统计失败'
        }
      }
    }
  }

  /**
   * 获取数据库路径
   */
  async getDBPath(): Promise<string> {
    try {
      this.checkElectronAPI()
      const result = await window.electronAPI.storage.getDBPath()
      if (result.ok) {
        return result.data
      }
      return 'Unknown'
    } catch (error) {
      return 'Unknown'
    }
  }
}
